from MBlog_backend.custom_response import custom_response
from category.models import category
from django.db.models import F, Count
import json


# Create your views here.
def list(request):
    category_list = category.objects.all().annotate(categoryName=F('category_name'), articleNum=Count('articles__id'))
    category_list = category_list.values('id', 'categoryName', 'description', 'avatar', 'articleNum')
    category_list = [i for i in category_list]
    resp = custom_response()
    if not category_list:
        resp.set_code('2001')
        resp.set_message('未查询到文章分类！')
    else:
        resp.data_update(category_list)
    return resp.response


def all(request):
    pass


def detail(request):
    body = json.loads(request.body)
    id = body.get('id')
    category_obj = category.objects.filter(id__exact=id).values('id').annotate(
        articleNum=Count('articles__id'),categoryName=F('category_name'))
    category_obj = category_obj.values('id', 'categoryName', 'articleNum','description')
    category_obj = category_obj.first()
    resp = custom_response()
    resp.data_update(category_obj)
    return resp.response
